import api from '@/api'
import { getToken } from '@/utils/auth'

const user = {
  namespaced: true,
  state: () => ({
    _id: "",
    nickname: "",
    avatarUrl: "",
    signature: "",
    email: "",
    sex: 0,
    fans: 0,
    createDate: null,
    lastLoginDate: null,
    follws: [],     // 关注列表
    favorites: [],  // 收藏列表，仅保存id
    history: [],    // 历史阅读记录（仅记录30个）
  }),
  mutations: {
    setInfo(state, user) {
      state._id = user._id
      state.nickname = user.nickname
      state.avatarUrl = user.avatarUrl
      state.signature = user.signature
      state.email = user.email
      state.sex = user.sex
      state.fans = user.fans || 0
      state.createDate = user.createDate || null
      state.lastLoginDate = user.lastLoginDate
      state.follws = user.follws || []
      state.favorites = user.favorites || []
      state.history = user.history || []
    }
  },
  actions: {
    loadInfo(context) {
      const hasToken = getToken()
      if (!hasToken) {
        console.log('not token')
        return
      }
      api.user.getProfile().then(result => {
        context.commit('setInfo', result.data.user)
      }).catch(err => {
        console.error('get user profile error:', err)
      })
    }
  },
  getters: {}
}

// call mutations:
// store.commit('user/xxx')
// store.commit('user/xxx',param)

export default user